package com.shanzhi.connection.common;

import com.shanzhi.connection.common.MapUtils;
import kong.unirest.*;

import java.io.File;
import java.util.Map;
import java.util.Set;

public class UnirestClientUtils {

    public static String postForUnirestString(String url, Map<String, String> headers, String jsonStr) throws Exception {
        RequestBodyEntity requestBodyEntity = Unirest.post(url)
                .header("User-Agent", "Apifox/1.0.0 (https://apifox.com)")
                .header("Content-Type", "application/json")
                .header("Accept", "*/*")
                .header("Connection", "keep-alive")
                .body(jsonStr)
                .connectTimeout(50000)
                .socketTimeout(120000);

        return executeRequestAndGetObject(requestBodyEntity, headers);
    }


    /**
     * 使用 Unirest 发送 POST 请求上传文件（multipart/form-data）
     *
     * @param url      请求地址
     * @param headers  请求头（如 Authorization）
     * @return 响应结果
     * @throws Exception 异常
     */
    public static String uploadFileWithUnirest(
            String url,
            Map<String, String> headers,
            Map<String, File> files) throws Exception {

        if (files == null || files.isEmpty()) {
            throw new IllegalArgumentException("Files map cannot be null or empty.");
        }

        HttpRequestWithBody httpRequestWithBody = Unirest.post(url)
                .header("User-Agent", "Apifox/1.0.0 (https://apifox.com)")
                .header("Content-Type", "multipart/form-data")
                .header("Accept", "*/*")
                .header("Connection", "keep-alive")
                .connectTimeout(50000)
                .socketTimeout(120000);

        for (Map.Entry<String, String> headerEntry : headers.entrySet()) {
            httpRequestWithBody.header(headerEntry.getKey(), headerEntry.getValue());
        }

        for (Map.Entry<String, File> fileEntry : files.entrySet()) {
            httpRequestWithBody.field("file", fileEntry.getValue(), "application/octet-stream");
        }

        HttpResponse<String> response = httpRequestWithBody.asString();

        if (!response.isSuccess()) {
            throw new Exception("HTTP request failed, status code: " + response.getStatus() + ", response: " + response.getBody());
        }

        return response.getBody();
    }
    public static String getForString(String url, Map<String, String> headers, Map<String, Object> params) throws Exception {
        HttpRequest httpRequest = Unirest.get(url)
                .header("User-Agent", "Apifox/1.0.0 (https://apifox.com)")
                .header("Accept", "*/*")
                .header("Connection", "keep-alive")
                .connectTimeout(50000)
                .socketTimeout(120000);

        if (params != null && !params.isEmpty()) {
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                httpRequest.queryString(entry.getKey(), entry.getValue().toString());
            }
        }

        return executeRequestAndGetObject(httpRequest, headers);
    }

    public static String putForUnirestString(String url, Map<String, String> headers, String jsonStr) throws Exception {
        RequestBodyEntity requestBodyEntity = Unirest.put(url)
                .header("User-Agent", "Apifox/1.0.0 (https://apifox.com)")
                .header("Content-Type", "application/json")
                .header("Accept", "*/*")
                .header("Connection", "keep-alive")
                .body(jsonStr)
                .connectTimeout(50000)
                .socketTimeout(120000);

        return executeRequestAndGetObject(requestBodyEntity, headers);
    }

    public static String deleteForString(String url, Map<String, String> headers, Map<String, Object> params) throws Exception {
        HttpRequestWithBody httpRequestWithBody = Unirest.delete(url)
                .header("User-Agent", "Apifox/1.0.0 (https://apifox.com)")
                .header("Accept", "*/*")
                .header("Connection", "keep-alive")
                .connectTimeout(50000)
                .socketTimeout(120000);

        if (params != null && !params.isEmpty()) {
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                httpRequestWithBody.queryString(entry.getKey(), entry.getValue().toString());
            }
        }

        return executeRequestAndGetObject(httpRequestWithBody, headers);
    }

    public static <T extends HttpRequest<T>> String executeRequestAndGetObject(T request, Map<String, String> headers) throws Exception {
        // 设置 Headers
        MapUtils.setHeaders(headers, request, (key, value, req) -> req.header(key, value));

        HttpResponse<String> response = request.asString();

        if (!response.isSuccess()) {
            throw new Exception("HTTP request failed, status code: " + response.getStatus() + ", response: " + response.getBody());
        }

        return response.getBody();
    }

}
